﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Tp.GUI.Base;
using TpBaseObjects.Objects;
using TpTools;
using TpBaseObjects;
using TpExtensions;
using TpData.Manager;
using Tp.GUI.Controller;
using TpContracts;


namespace Tp.GUI.Dialog {

    public partial class Rechnung : TpBase {

        #region Members

        RechnungController controller;
        private const string errType = "Err";
        private const string logType = "Log";
        private const string logArea = "Tp.GUI.Dialog.Rechnung";

        #endregion

        #region Constructor

        public Rechnung() {
            this.controller = new RechnungController(this);
            InitializeComponent();
        }

        public Rechnung(InvoiceObject invoice)
            : this() {
            MyModel = invoice;
            SetStartValues();
            SetRechnungsValues(MyModel);
            LockOrganisation();
        }

        #endregion

        #region Properties

        public bool Cancel {
            get;
            set;
        }

        public string SelectedType {
            get { return this.selectedType; }
            set { this.selectedType = value; }
        }

        public int Versand {
            get { return this.versand; }
            set { this.versand = value; }
        }

        public Recipient MyRecipient {
            get { return this.myRecipient; }
        }

        public InvoiceObject MyModel {
            get;
            set;
        }

        public List<Beilage> Beilagen {
            get;
            set;
        }

        #endregion

        #region Methods

        private bool CheckForm() {
            bool ret = false;
            if (this.rpZahlung.Selected == 0) {
                MessageBox.Show("Zahlungsart wurde nicht gewählt!", MyModel.ProjektBezeichnung, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            if (this.rpVersand.Selected == 0) {
                MessageBox.Show("Versandart wurde nicht gewählt!", MyModel.ProjektBezeichnung, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }

            if (Office.CheckLiquiIsOpen(MyModel.Rechnungsdatum.Year.ToString().Right(2), Tp.Properties.Settings.Default.PathRewe)) {
                string msg = MyModel.Rechnungsdatum.Year.ToString().Right(2) + @"\Liqui.xlsm ist geöffnet. Bitte zuerst diese Datei schließen!";
                MessageBox.Show(msg, MyModel.ProjektBezeichnung, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }


            if (Office.CheckArJJIsOpen(MyModel.Rechnungsdatum.Year.ToString().Right(2), Tp.Properties.Settings.Default.PathRewe)) {
                string msg = @"Ar" + MyModel.Rechnungsdatum.Year.ToString().Right(2) + ".xlsm ist geöffnet. Bitte zuerst diese Datei schließen!";
                MessageBox.Show(msg, MyModel.ProjektBezeichnung, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }

            if (MyModel.UstPercent == 0 && (MyModel.UID == null || MyModel.UID.Length < 3)) {
                string msg = @"UID muss angegben werden!";
                MessageBox.Show(msg, MyModel.ProjektBezeichnung, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }

            if (MyModel.RechnungsBetrag > 12000.0 && MyModel.IsBusiness && (MyModel.UID == null || MyModel.UID.Length < 3)) {
                string msg = @"UID muss angegben werden!";
                MessageBox.Show(msg, MyModel.ProjektBezeichnung, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            if (MyModel.PersonenKonto == null || MyModel.PersonenKonto == "") {
                string msg = @"Debitorenkonto muss angegben werden!";
                MessageBox.Show(msg, MyModel.ProjektBezeichnung, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            if (MyModel.SachKonto == null || MyModel.SachKonto == "") {
                string msg = @"SachKonto muss angegben werden!";
                MessageBox.Show(msg, MyModel.ProjektBezeichnung, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            return ret;
        }

        private void btnAddBeilage(object sender, EventArgs e) {
            try {
                if (this.openFileDialog1.ShowDialog() == DialogResult.OK) {
                    string fileBezeichnung = InputBox.ShowDialog("Dateibezeichnung", "Beilage");

                    Beilage bel = new Beilage();
                    bel.FullFileName = openFileDialog1.FileName;
                    bel.IsChecked = true;
                    if (fileBezeichnung != null && fileBezeichnung.Length > 0) {
                        bel.BeilagenText = fileBezeichnung + " (" + bel.FileName + ")";
                    } else {
                        bel.BeilagenText = bel.FileName;
                    }
                    if (this.MyModel.Beilagen == null) {
                        this.MyModel.Beilagen = new List<Beilage>();
                    }
                    this.MyModel.Beilagen.Add(bel);
                    this.beilagenBindingsource.Add(bel);
                }
            } catch (Exception ex) {
                MessageBox.Show("Error" + ex.Message);
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, ex.Message, true);
            }
        }

        private void LockOrganisation() {
            this.txtOrg.ReadOnly = true;
            this.txtStrasse.ReadOnly = true;
            this.txtPlzOrt.ReadOnly = true;
            this.txtAuftraggeberMail.ReadOnly = true;

        }

        private void SetControlsDisEnabled() {
            //Auftraggeber
            this.cboAFPerson.Enabled = this.chkZHdn.Checked;

            //Rechnungsempfänger
            this.txtRePerson.Enabled = this.chkReZHdn.Checked;

            //Auftragsdaten
            this.dateTimePicker3.Enabled = MyModel.AFAbDatum != new DateTime(1900, 1, 1);
            this.dateTimePicker2.Enabled = rbAufTel.Checked;
            this.cbAFTel.Enabled = rbAufTel.Checked;
            this.dateTimePicker4.Enabled = rbAufPers.Checked;
            this.cbAFPers.Enabled = rbAufPers.Checked;
            if (MyModel.AFAbDatum.Value.Year > 1900) {
                this.rpAuftrag.Enabled = false;
            } else {
                this.rpAuftrag.Enabled = true;
            }

            if(MyModel.AFDurchfuehrungVon == new DateTime(1900,1,1)) {
                MyModel.AFDurchfuehrungVon = DateTime.Now.AddDays(1).Date;
            }

            //Beilagen

        }

        private void SetStartValues() {
            if (MyModel == null) {
                MyModel = new InvoiceObject();
                MyModel.RechnungVersand = Global.InvoiceSendType.Persoenlich;
                MyModel.ZahlArt = Global.InvoicePayType.BarNachMontage;
                MyModel.AufstragsArt = Global.AuftragsArt.Telefonisch;

                this.cboAFPerson.DataSource = MyModel.MyPersons.ToString();
                this.cbAFTel.DataSource = MyModel.MyPersons.ToString();
                this.cbAFPers.DataSource = MyModel.MyPersons.ToString();

            }
            this.invoiceBindingSource.DataSource = MyModel;

            this.rpVersand.DataBindings.Add("Selected", MyModel, "RechnungVersand");
            this.rpZahlung.DataBindings.Add("Selected", MyModel, "ZahlArt");
            this.rpAuftrag.DataBindings.Add("Selected", MyModel, "AufstragsArt");

            if (MyModel.MyPersons != null) {
                //this.personBindingSource.DataSource = MyModel.MyPersons.ToString();
                this.cboAFPerson.DataSource = MyModel.MyPersons;
                this.cbAFTel.DataSource = MyModel.MyPersons;
                this.cbAFPers.DataSource = MyModel.MyPersons;
            }

            if (MyModel.Kunde.Left(2) == "Wh") {
                Organisation whOrg = OrganisationDataManager.LoadOrganisation("Wunschhaus", "Z1");
                if (whOrg != null) {
                    this.MyModel.ReEmpfaenger = whOrg.Prefix.AddSpace() + whOrg.OrgName.AddSpace() + whOrg.ZusätzeFW.AddSpace() + whOrg.RechtsForm;
                    this.MyModel.RePlzOrt = whOrg.Plz.AddSpace() + whOrg.Ort;
                    this.MyModel.ReStrasse = whOrg.Straße;
                    this.MyModel.ReEmpfaengerMail = whOrg.EMail;
                    this.MyModel.SkontoProzent1 = 2.0;
                    this.MyModel.SkontoTage1 = 14;
                    this.MyModel.SkontoTage2 = 30;
                    this.MyModel.ZahlArt = Global.InvoicePayType.NachRechnungserhalt;
                }
            }

            //if (MyModel.SkontoProzent1 != 0.0) {
            //    MyModel.SkontoTage2 = 30;
            //}

            //this.beilagenBindingsource.DataSource = MyModel.Beilagen;
            if (MyModel.Beilagen != null) {
                foreach (Beilage bel in MyModel.Beilagen) {
                    this.beilagenBindingsource.Add(bel);
                }
            }

            Cancel = true;

            SetControlsDisEnabled();
        }

        private void SetRechnungsValues(InvoiceObject myModel) {
            if (myModel.SummeNetto == 0) {
                this.txtSummeNetto.Enabled = false;
                //this.txtSummeNetto.Enabled = true;
                //this.txtSummeNetto.BackColor = Color.Yellow;
            } else {
                this.txtSummeNetto.Enabled = false;
            }
            if (myModel.SummeBrutto == 0) {
                this.txtSummeBrutto.Enabled = false;
                //this.txtSummeBrutto.Enabled = true;
                //this.txtSummeBrutto.BackColor = Color.Yellow;
            } else {
                this.txtSummeBrutto.Enabled = false;
            }
            if (myModel.Ust == 0) {
                this.txtUstAmount.Enabled = false;
                //this.txtUstAmount.Enabled = true;
                //this.txtUstAmount.BackColor = Color.Yellow;
            } else {
                this.txtUstAmount.Enabled = false;
            }
            if (myModel.AKontoBetrag == 0) {
                this.txtAkonto.Enabled = false;
                //this.txtAkonto.Enabled = true;
                //this.txtAkonto.BackColor = Color.Yellow;
            } else {
                this.txtAkonto.Enabled = false;
            }
            if (myModel.SkontoBetrag == 0 & myModel.IsBusiness) {
                this.txtSkontoProzent.Enabled = false;
                this.txtSkonto.Enabled = false;
                this.txtSkontoTage1.Enabled = false;
                this.txtSkontoTage2.Enabled = false;

                //this.txtSkontoProzent.Enabled = true;
                //this.txtSkontoProzent.BackColor = Color.Yellow;
                //this.txtSkonto.Enabled = true;
                //this.txtSkonto.BackColor = Color.Yellow;
                //this.txtSkontoTage1.Enabled = true;
                //this.txtSkontoTage1.BackColor = Color.Yellow;
                //this.txtSkontoTage2.Enabled = true;
                //this.txtSkontoTage2.BackColor = Color.Yellow;
            } else {
                this.txtSkontoProzent.Enabled = false;
                this.txtSkonto.Enabled = false;
                this.txtSkontoTage1.Enabled = false;
                this.txtSkontoTage2.Enabled = false;

            }

            //this.cboSachkonto.DataSource = MyModel.SachKonto;
        }

        private void SetAuftragsDatum() {
            if (this.rbAufPers.Checked) {
                MyModel.AFAuftragPers = true;
                MyModel.AufstragsArt = Global.AuftragsArt.Persoenlich;
            } else {
                MyModel.AFAuftragPers = false;
            }
            if (this.rbAufTel.Checked) {
                MyModel.AFAuftragTelefon = true;
                MyModel.AufstragsArt = Global.AuftragsArt.Telefonisch;
            } else {
                MyModel.AFAuftragTelefon = false;
            }

        }

        private void DisEnableAuftraggeber(bool disEnabled) {
            this.txtOrg.Enabled = disEnabled;
            this.chkZHdn.Enabled = disEnabled;
            this.txtStrasse.Enabled = disEnabled;
            this.txtPlzOrt.Enabled = disEnabled;

        }

        private void SetFormClose() {
            if (this.Beilagen != null) {
                this.Beilagen.Clear();
            }
            if (this.MyModel.Beilagen != null) {
                this.MyModel.Beilagen.Clear();
            }

            foreach (Beilage b1 in this.beilagenBindingsource) {

                if (this.Beilagen == null) {
                    this.Beilagen = new List<Beilage>();
                }
                if (this.MyModel.Beilagen == null) {
                    this.MyModel.Beilagen = new List<Beilage>();
                }
                if (b1.IsChecked) {
                    this.Beilagen.Add(b1);
                }
                this.MyModel.Beilagen.Add(b1);

            }

            if (this.MyModel.ReEmpfaenger != null) {
                this.myRecipient.EMail = this.MyModel.ReEmpfaengerMail;
                this.myRecipient.Betreff = this.MyModel.ReBetreff;
            } else {
                this.myRecipient.EMail = this.MyModel.AuftraggeberMail;
                this.myRecipient.Betreff = "Rechnung " + this.MyModel.RechnungsNummer.ToString();
            }
        }

        private void Rechnung_FormClosed(object sender, FormClosedEventArgs e) {
            SetFormClose();
        }

        private void btnCancel_Click(object sender, EventArgs e) {
            Cancel = true;
            this.Close();
        }

        private void btnOk_Click(object sender, EventArgs e) {

            if (!CheckForm()) {
                Cancel = false;
                this.Close();
            }
        }

        private void rpVersand_SelectedChanged(object sender, EventArgs e) {
            MyModel.RechnungVersand = (Global.InvoiceSendType)this.rpVersand.Selected;
        }

        private void rpZahlung_SelectedChanged(object sender, EventArgs e) {
            MyModel.ZahlArt = (Global.InvoicePayType)this.rpZahlung.Selected;
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e) {
            SetControlsDisEnabled();
        }

        private void checkBox7_CheckedChanged(object sender, EventArgs e) {
            SetControlsDisEnabled();
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e) {
            SetControlsDisEnabled();
        }

        private void chkLS_CheckedChanged(object sender, EventArgs e) {
            SetControlsDisEnabled();
        }

        private void chkAP_CheckedChanged(object sender, EventArgs e) {
            SetControlsDisEnabled();
        }

        private void chkZusatzText_CheckedChanged(object sender, EventArgs e) {
            SetControlsDisEnabled();
        }

        private void chkDatei_CheckedChanged(object sender, EventArgs e) {
            SetControlsDisEnabled();
        }

        private void chkReZHdn_CheckedChanged(object sender, EventArgs e) {
            SetControlsDisEnabled();
        }

        private void chkZHdn_CheckedChanged(object sender, EventArgs e) {
            SetControlsDisEnabled();
        }

        private void txtUstPercent_Validated(object sender, EventArgs e) {
            double invoiceAmount = (String.IsNullOrEmpty(this.txtZahlung.Text) ? 0 : Convert.ToDouble(this.txtZahlung.Text));
            //double ustPercent = (String.IsNullOrEmpty(this.txtUstPercent.Text) ? 0 : Convert.ToDouble(this.txtUstPercent.Text));
            //MyModel.Ust = invoiceAmount - (invoiceAmount / (1 + (ustPercent / 100)));
            //MyModel.UstPercent = ustPercent;
            //this.txtUstAmount.Text = MyModel.Ust.ToString("N", CultureInfo.InvariantCulture);
            //this.txtUstPercent.Text = MyModel.UstPercent.ToString("N", CultureInfo.InvariantCulture);
        }

        private void rpAuftrag_SelectedChanged(object sender, EventArgs e) {
            SetControlsDisEnabled();
            SetAuftragsDatum();
        }

        private void txtReEmpf_TextChanged(object sender, EventArgs e) {
            if (this.txtReEmpf.Text.Length > 0) {
                DisEnableAuftraggeber(false);
            } else {
                DisEnableAuftraggeber(true);
            }
        }

        private void txtAkonto_Validated(object sender, EventArgs e) {
            //MyModel.RechnungsBetrag = MyModel.SummeBrutto - (double)MyModel.AKontoBetrag;
        }

        #endregion

    }
}
